package commerce.action;

import org.apache.struts2.ServletActionContext;

import site.service.ShopSiteCreateService;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;

import commerce.business.CommerceBusiness;
import commerce.hibernate.po.*;

public class ShopRegAction extends ActionSupport{
	private Shop shop;
	private CommerceBusiness cb;
	private String msg;
	private String state;
	public Shop getShop()
	{
		return this.shop;
	}
	public void setShop(Shop shop)
	{
		this.shop=shop;
	}
	public String getMsg()
	{
		return this.msg;
	}
	public void setMsg(String msg)
	{
		this.msg=msg;
	}
	public String getState()
	{
		return this.state;
	}
	public void setState(String state)
	{
		this.state=state;
	}
	
	/*
	 * 验证商铺名称的有效性，例如是否有重复名称
	 */
	public String validateShopName()
	{
		this.msg="";
		if(getShop()==null)
		{
			this.msg="username cannot be blank!";
			this.state="0";
			return SUCCESS;
		}
		String shopName=getShop().getShopName();
		//根据店铺名字查找店铺
		cb=new CommerceBusiness();
		Shop s=cb.getShopByName(shopName);
		if(s!=null)
		{
			this.msg="name "+shopName+" has been existed,please choose another one!";
			this.state="0";
			return SUCCESS;
		}
		else
		{
			this.msg="ok!";
			this.state="1";
			return SUCCESS;
		}
	}
	/*
	 * 验证商铺名称的有效性，例如是否有重复名称
	 */
	public String validateAdminName()
	{
		this.msg="";
		if(getShop()==null)
		{
			this.msg="admin cannot be blank!";
			this.state="0";
			return SUCCESS;
		}
		String adminName=getShop().getAdminName();
		//根据管理员账户名称获取店铺
		cb=new CommerceBusiness();
		Shop s=cb.getShopByAdminName(adminName);
		if(s!=null)
		{
			this.msg="name "+adminName+" has been existed,please choose another one!";
			this.state="0";
			return SUCCESS;
		}
		else
		{
			this.msg="ok!";
			this.state="1";
			return SUCCESS;
		}
	}
	/*
	 * (non-Javadoc)
	 * @see com.opensymphony.xwork2.ActionSupport#execute()
	 */
	public String execute() throws Exception
	{
		if(getShop()==null)
		{
			this.state="0";
			this.msg="reg failed!";
			return Action.SUCCESS;
		}
		cb=new CommerceBusiness();
		if(cb.saveShop(shop)==true)
		{
			this.state="1";
			this.msg="reg success!";
			refeshShopHtml();
		}
		else
		{
			this.state="0";
			this.msg="reg failed!";
		}
		return SUCCESS;
	}
	
	
	private void refeshShopHtml() {
		String realPath = ServletActionContext.getServletContext().getRealPath(
				"/test/commerce/html/shop.html");
		new ShopSiteCreateService().makeShopSite(realPath, true);
	}
}
